<!--<template>-->
<!--  <div style="margin: 5px 5px;">-->
<!--    <el-row :gutter="20">-->
<!--      &lt;!&ndash;      <el-col :span="5" style="margin-top: 10px;padding-right: 0; padding-left: 30px;">&ndash;&gt;-->
<!--      &lt;!&ndash;        <div slot="header" class="clearfix">&ndash;&gt;-->
<!--      &lt;!&ndash;          <span>部门</span>&ndash;&gt;-->
<!--      &lt;!&ndash;        </div>&ndash;&gt;-->
<!--      &lt;!&ndash;        <div class="block department">&ndash;&gt;-->
<!--      &lt;!&ndash;          <el-tree&ndash;&gt;-->
<!--      &lt;!&ndash;            :data="departments"&ndash;&gt;-->
<!--      &lt;!&ndash;            :props="departmentProps"&ndash;&gt;-->
<!--      &lt;!&ndash;            node-key="id"&ndash;&gt;-->
<!--      &lt;!&ndash;            default-expand-all&ndash;&gt;-->
<!--      &lt;!&ndash;            highlight-current&ndash;&gt;-->
<!--      &lt;!&ndash;            :expand-on-click-node="false"&ndash;&gt;-->
<!--      &lt;!&ndash;            @node-click="getDepartmentUsers"&ndash;&gt;-->
<!--      &lt;!&ndash;          />&ndash;&gt;-->
<!--      &lt;!&ndash;        </div>&ndash;&gt;-->
<!--      &lt;!&ndash;      </el-col>&ndash;&gt;-->
<!--      <el-col style="padding-left: 0;">-->
<!--        <catch-table-->
<!--          v-if="table"-->
<!--          :ref="table.ref"-->
<!--          :headers="table.headers"-->
<!--          :border="true"-->
<!--          :search="table.search"-->
<!--          :filter-params="table.filterParams"-->
<!--          :form-create="formCreate"-->
<!--          :actions="table.actions"-->
<!--          :table-events="table.events"-->
<!--          :api-route="table.apiRoute"-->
<!--          :selectable="selectable"-->
<!--        />-->
<!--      </el-col>-->
<!--    </el-row>-->
<!--  </div>-->
<!--</template>-->
<!--<script>-->
<!--import renderTable from '@/views/render-table-form'-->
<!--import status from './component/status'-->

<!--export default {-->
<!--  components: {-->
<!--    // eslint-disable-next-line vue/no-unused-components-->
<!--    status-->
<!--  },-->
<!--  mixins: [renderTable],-->

<!--  data() {-->
<!--    return {-->
<!--      tableFrom: 'table/permissions/user',-->
<!--      // 部门-->
<!--      departments: [],-->
<!--      departmentProps: {-->
<!--        label: 'department_name'-->
<!--      }-->
<!--    }-->
<!--  },-->
<!--  created() {-->
<!--    this.$http.get('departments').then(response => {-->
<!--      this.departments = response.data-->
<!--    })-->
<!--  },-->
<!--  methods: {-->
<!--    // 获取部门用户-->
<!--    getDepartmentUsers(data, node, self) {-->
<!--      this.$refs[this.table.ref].queryParams.department_id = data.id-->
<!--      this.$refs[this.table.ref].handleSearch()-->
<!--    },-->
<!--    selectable(row) {-->
<!--      return row.id !== 1-->
<!--    },-->

<!--    beforeSubmit(row) {-->
<!--      if (row.form.department_id instanceof Array) {-->
<!--        row.form.department_id = row.form.department_id.length > 0 ? row.form.department_id.pop() : 0-->
<!--      }-->
<!--      return row-->
<!--    },-->

<!--    beforeDelete(row) {-->
<!--      if (row.id === 1) {-->
<!--        this.$message.error('超级管理员不允许删除')-->

<!--        return false-->
<!--      }-->
<!--    },-->
<!--    beforeCreate() {-->
<!--      this.formCreate.fApi.updateValidate('password', [{ required: true, message: '密码必须填写' }], true)-->
<!--      this.formCreate.fApi.refresh()-->
<!--    },-->
<!--    beforeUpdate() {-->
<!--      this.formCreate.fApi.updateValidate('password', [{ required: false }])-->
<!--    }-->
<!--  }-->
<!--}-->
<!--</script>-->

<!--<style>-->
<!--  .custom-tree-node {-->
<!--    flex: 1;-->
<!--    display: flex;-->
<!--    align-items: center;-->
<!--    justify-content: space-between;-->
<!--    font-size: 14px;-->
<!--    padding-right: 8px;-->
<!--  }-->
<!--  .department .el-tree {-->
<!--    padding: 10px 10px;-->
<!--    height: 360px;-->
<!--  }-->
<!--  .department .el-tree .el-tree-node__content {-->
<!--      height: 35px;-->
<!--  }-->

<!--  .department .el-tree .el-tree-node__content .el-tree-node__label {-->
<!--    font-size: 15px;-->
<!--  }-->
<!--</style>-->
<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="企业名称" prop="merchant_name">
        <el-input
          v-model="queryParams.merchant_name"
          placeholder="请输入企业名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small">
          <el-option
            v-for="(dict,index) in statusOptions"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="类型" clearable size="small">
            <el-option
              v-for="(dict,index) in typeOptions"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form-item></el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-action="'user@createUser'"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleCreate({},'新建')"
        >新建
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" style="width: 100%;">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="用户类型" align="center" :formatter="statusFormat" />
      <!--      <el-table-column type="用户头像" width="50" align="center" prop="avatar" />-->
      <el-table-column label="企业名称" align="center" prop="merchant_name" :show-overflow-tooltip="true" />
      <el-table-column label="用户状态" align="center">
        <template v-slot="scope">
          <el-switch
            v-if="scope.row.id !== 1"
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="disOrEnable($event,scope.row)"
          />
          <el-switch
            v-else
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <el-button
            v-action="'user@updateUser'"
            size="mini"
            type="primary"
            :disabled="scope.row.id === 1"
            @click="handleCreate(scope.row,'编辑')"
          >编辑</el-button>
          <el-button
            v-action="'user@delUser'"
            size="mini"
            type="danger"
            :disabled="scope.row.id === 1"
            @click="delUser(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
    <!-- 新增 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="form.id === undefined ? rules : updateRules" label-width="100px" class="demo-ruleForm">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="form.id!==undefined" />
        </el-form-item>

        <el-form-item label="用户类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width:100%">
            <el-option
              v-for="(dict,index) in typeOptions"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" type="password" auto-complete="new-password" />
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPass">
          <el-input v-model="form.checkPass" type="password" auto-complete="new-password" />
        </el-form-item>

        <el-form-item label="公司英文简称" prop="co_code">
          <el-input v-model="form.co_code" />
        </el-form-item>

        <el-form-item label="企业全称" prop="merchant_name">
          <el-input v-model="form.merchant_name" :disabled="form.merchant_id!==undefined&&form.merchant_id!==null&&form.merchant_id!==''" />
        </el-form-item>

        <!--        <el-form-item label="报关模式" prop="push_way">-->
        <!--          <el-select v-model="form.push_way" placeholder="请选择类型" style="width:100%">-->
        <!--            <el-option-->
        <!--              v-for="(dict,index) in pushWayOptions"-->
        <!--              :key="index"-->
        <!--              :label="dict.label"-->
        <!--              :value="dict.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="电商平台名称" prop="ebp_name">
          <el-input v-model="form.ebp_name" />
        </el-form-item>

        <el-form-item label="电商平台代码" prop="ebp_code">
          <el-input v-model="form.ebp_code" />
        </el-form-item>

        <el-form-item label="巧易商户ID" prop="qekj_tenant_id">
          <el-input v-model="form.qekj_tenant_id" type="number" />
        </el-form-item>

        <el-form-item label="预授信金额" prop="credit_amount">
          <el-input v-model="form.credit_amount" type="number" />
        </el-form-item>

        <!--        <el-form-item label="电商企业名称" prop="ebc_name">-->
        <!--          <el-input v-model="form.ebc_name" />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="电商企业代码" prop="ebc_code">-->
        <!--          <el-input v-model="form.ebc_code" />-->
        <!--        </el-form-item>-->

        <el-form-item label="用户角色" prop="roles">
          <el-tree
            ref="tree"
            :data="roles"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-checked-keys="form.roles"
            default-expand-all
            :expand-on-click-node="false"
            :render-content="renderContent"
            @check-change="checkChange"
          />
        </el-form-item>
        <el-row>
          <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
            <el-col :span="24">
              <el-button type="primary" size="medium" @click="submitForm('form')">{{ title }}</el-button>
              <el-button size="medium" @click="open=false">取消</el-button>

            </el-col>
          </el-row>
        </el-row>
      </el-form>
    </el-dialog>
  </div>

</template>
<style>
.el-input__inner {
  width: 90%;
}
.el-input__suffix {
  right: 10%;
}
</style>
<script>
import { list, myRoles, createUser, updateUser, delUser, switchUser } from '@/api/user'
export default {
  name: 'Index',
  data() {
    var checkMerchant = (rule, value, callback) => {
      // if (value) {
      //   var myreg = /^[\u4e00-\u9fa5\(\)（）\da-zA-Z&]{4,30}[公司|集团|企业|中心|所|厂|社]$/gi
      //   if (!myreg.test(value)) {
      //     callback(new Error('企业名称不合法'))
      //   }
      // }
      if (this.form.type === 2 && !value) {
        callback(new Error('商户类型时，企业名称不能为空'))
      } else {
        callback()
      }
    }
    var checkPushWay = (rule, value, callback) => {
      if (this.form.type === 2 && !value) {
        callback(new Error('商户类型时，报关模式不能为空'))
      } else {
        callback()
      }
    }
    var checkPass2 = (rule, value, callback) => {
      if (this.form.password && this.form.password !== '') {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'))
        }
      }
      callback()
    }
    var checkRoles = (rule, value, callback) => {
      if (this.$refs.tree.getCheckedKeys().length === 1) {
        this.form.roles = this.$refs.tree.getCheckedKeys()
        callback()
      } else if (this.$refs.tree.getCheckedKeys().length === 0) {
        callback(new Error('要选择一个角色'))
      } else {
        callback(new Error('只需要选择一个角色'))
      }
    }
    return {
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      roles: [],
      info: '',
      // 用户状态
      statusOptions: [
        { 'value': 1, 'label': '正常' },
        { 'value': 2, 'label': '禁用' }
      ],
      // 类型状态
      typeOptions: [
        { 'value': 1, 'label': '管理员' },
        { 'value': 2, 'label': '商户' }
      ],
      // 报关模式
      pushWayOptions: [
        { 'value': 1, 'label': '服务商模式' },
        { 'value': 2, 'label': '商户模式' }
      ],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        status: undefined,
        merchant_name: undefined,
        type: undefined
      },
      form: {},
      show: false,
      ids: [],
      updateRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        password: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { validator: checkPass2, trigger: 'blur' }
        ],
        merchant_name: [
          { validator: checkMerchant, trigger: 'blur' }
        ],
        push_way: [
          { validator: checkPushWay, trigger: 'change' }
        ],
        ebp_name: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        ebp_code: [
          { len: 10, message: '长度为 10 个字符', trigger: 'blur' }
        ],
        ebc_name: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        ebc_code: [
          { len: 10, message: '长度 10 个字符', trigger: 'blur' }
        ],
        roles: [
          { required: true, validator: checkRoles }
        ],
        co_code: [
          { required: true, message: '请输入公司英文简称2-5个大写字母', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: checkPass2, trigger: 'blur' }
        ],
        merchant_name: [
          { validator: checkMerchant, trigger: 'blur' }
        ],
        push_way: [
          { validator: checkPushWay, trigger: 'change' }
        ],
        ebp_name: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        ebp_code: [
          { len: 10, message: '长度为 10 个字符', trigger: 'blur' }
        ],
        ebc_name: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        ebc_code: [
          { len: 10, message: '长度 10 个字符', trigger: 'blur' }
        ],
        roles: [
          { required: true, validator: checkRoles }
        ],
        co_code: [
          // { required: true, message: '请输入公司英文简称2-5个大写字母', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /** 详情 */
    detail(row) {
      // orderInfo({ orderId: row.orderId, type: 1 }).then(response => {
      //   if (response.code === 10000) {
      //     this.form = response.data
      //     this.show = true
      //   }
      // })
    },
    /** 打开 */
    handleCreate(row, title) {
      const that = this
      myRoles({}).then(response => {
        console.log(JSON.stringify(row))
        that.roles = response.data
        if (that.$refs['form']) {
          that.$refs['form'].clearValidate()
        }
        that.form = row || {}
        that.title = title
        that.open = true
      })
    },
    /** 查询清单列表 */
    getList() {
      this.loading = true
      // console.log(this.queryParams)
      list(this.queryParams).then(response => {
        // console.log(response)
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    checkChange(data, checked) {
      if (checked === true) {
        this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.setChecked(data, true)
      }
    },
    /** 状态字典翻译 */
    statusFormat(row, column) {
      let type = row.type
      for (const d of this.typeOptions) {
        if (row.type === d.value) {
          type = d.label
          break
        }
      }
      return type
    },
    // 用户状态
    disOrEnable(v, row) {
      const that = this
      const data = {}
      data.status = v
      data.id = row.id
      switchUser(data).then(response => {
        // console.log(response)
        that.$message.success(response.message)
        that.getList()
      })
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!that.form.id) {
            createUser(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          } else {
            updateUser(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          }
        } else {
          return false
        }
      })
    },
    delUser(row) {
      const that = this
      that.$confirm('是否删除用户' + row.username, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delUser({ id: row.id }).then(response => {
          that.$message.success(response.message)
          that.getList()
        })
      }).catch(() => {
      })
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class='custom-tree-node'>
          <span>{data.role_name}</span>
        </span>)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        username: undefined,
        status: undefined,
        merchant_name: undefined,
        type: undefined
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.multiple = !selection.length
    }
  }
}
</script>

